package com.tarena.lbs.basic.web.filter;


import com.tarena.lbs.basic.web.utils.ThreadLocalUtils;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Slf4j
//@Component
public class UserFilter implements Filter {
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("你好,我是第一个过滤器 进入");
        //1.从请求获取请求头
        UserPrinciple userPrinciple=null;
        if(servletRequest instanceof HttpServletRequest){
            HttpServletRequest request=(HttpServletRequest) servletRequest;
            //2. 拿出头
            String jwt = request.getHeader("Authorization");
            if (!StringUtils.isEmpty(jwt)){
                try{
                    userPrinciple= jwtEncoder.getLoginFromToken(jwt,UserPrinciple.class);
                }catch (Exception e){
                    log.error("解析token失败",e);
                }
            }
        }
        //threadlocal传递数据
        ThreadLocalUtils.setValue(userPrinciple);
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("你好,我是第一个过滤器 出去");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
